//
//  HomeViewController.m
//  BYX
//
//  Created by dllo on 15/8/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "HomeViewController.h"
#import "PicView.h"
#import "ColumnView.h"
#import "HomeModel.h"
#import "Define.h"
#import "WebViewController.h"
#import "AsyncConnection.h"
#import "CompanyCell.h"
#import "CompanyViewController.h"
#import "DiseaseListViewController.h"
#import "ColumnDrugListViewController.h"
#import "DrugListViewController.h"
#import "DKNightVersion.h"
#import "UIImageView+NightImage.h"
#import "YAScrollSegmentControl.h"
#import "Reachability.h"
#import "MoreProductCell.h"
#import "HomeHouseCell.h"
#import "InformationController.h"
#import "HomeHouseCell.h"
#import "FirstSearchController.h"
@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,PicViewDelegate,ColumnViewDelegate,YAScrollSegmentControlDelegate>

@property (nonatomic, retain) YAScrollSegmentControl *scrollSC;
@property (nonatomic, retain) NSMutableArray *drugIDArray;
@property (nonatomic, retain) NSArray *searchArray;
@property (nonatomic, retain) NSMutableArray *ziXunArray;
@property (nonatomic, retain) NSMutableArray *secondZiXunArray;
@property (nonatomic, retain) NSMutableArray *tableArray; //合作单位
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *imageArray; //轮番图
@property (nonatomic, retain) NSMutableArray *thirdArray;
@property (nonatomic, retain) NSMutableArray *chinaDrugArray;
@property (nonatomic, retain) NSMutableArray *foreignDrugArray;
@property (nonatomic, retain) UIView *backView;

@end

@implementation HomeViewController

-(void)dealloc
{
    
    [_backView release];
    [_scrollSC release];
    [_ziXunArray release];
    [_secondZiXunArray release];
    [_chinaDrugArray release];
    [_searchArray release];
    [_drugIDArray release];
    [_thirdArray release];
    [_imageArray release];
    [_tableArray release];
    [_tableView release];
   

    [super dealloc];
}
       
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super  initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.chinaDrugArray = [NSMutableArray array];
        self.tableArray = [NSMutableArray array];
        self.imageArray = [NSMutableArray array];
        self.ziXunArray = [NSMutableArray array];
        self.secondZiXunArray = [NSMutableArray array];
        self.thirdArray = [NSMutableArray array];
        self.drugIDArray = [NSMutableArray array];
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:86/255.0 green:137/255.0 blue:156/255.0 alpha:1];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 60, 0, 60, 33)];
    titleLabel.text = @"首页";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont fontWithName:@"Baskerville-SemiBold" size:20];
    self.navigationItem.titleView = titleLabel;
    [titleLabel release];

    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    searchButton.frame = CGRectMake(self.view.frame.size.width - 20, 10, 20, 20);
    [searchButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"sousuo" ofType:@"png"]] forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];
    self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
    [self createNavigationBar];
    [self createTableView];
   
    
    self.drugIDArray = [NSMutableArray arrayWithObjects:@"%E6%AD%A5%E9%95%BF",@"%E7%A7%91%E4%BC%A6",@"%E6%81%92%E7%91%9E",@"%E7%BD%97%E6%B0%8F", nil];
    self.scrollSC = [[YAScrollSegmentControl alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    _scrollSC.delegate = self;
    _scrollSC.selected = YES;
    _scrollSC.selectedIndex = 0;
    [_scrollSC setTitleColor:[UIColor purpleColor] forState:UIControlStateSelected];
    
    [_scrollSC setFont:[UIFont systemFontOfSize:15]];
     [self handleData];
}

- (void)viewWillAppear:(BOOL)animated
{

    [self webConnection];
    [self.tableView reloadData];

}


//搜索的接口
- (void)webConnection
{
 
    
    [AsyncConnection asyncConnectionWithUrl:@"http://mobi.111.com.cn/ApiControl?method=products.category.getcategory&method=products.category.getcategory&categoryversion=2&searchtype=1&fatherid=-1&categorytype=1&encryptversion=2&sign=6182A5315111900ECAC45166C1FC2EE9&timestamp=20150919092809&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854" name:@"searchFile" parameters:nil block:^(id data) {
        
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"categoryinfo"];
        self.searchArray = array;
        
    } get:@"post"];
    
    
}

//点击搜索按钮，将数组传送过去
- (void)searchButtonAction:(id)sender
{

    FirstSearchController *firstV = [[FirstSearchController alloc] init];
    [firstV getTabC:self.tabBarController nav:self.navigationController];
    [firstV getArray:_searchArray];
    [self.navigationController pushViewController:firstV animated:YES];
    [firstV release];

}

#pragma mark -
#pragma mark 导航栏搜索设置
/**
 *  创建searchBar
 */
- (void)createNavigationBar
{
    UIApplication *app =[UIApplication sharedApplication];
    [app setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    
    
    
}
/**
 *  searchBar 协议方法
 *
 *  @param searchBar 开始编辑 出现取消按钮 创建view 覆盖首页的tableView
 *
 *  @return yes
 */

/**
 *
 *
 *  @param searchBar
 *  @param searchText  输入搜索字 解析数据 创建自定义tableView
 */


#pragma mark -
#pragma mark 数据请求 解析

- (void)handleData
{
    
    [AsyncConnection asyncConnectionWithUrl:@"http://askapi.jianke.com/app/article/GetNewsHomeList" name:@"myPic" parameters:nil block:^(id data) {
        
        NSArray *array1 = [[data objectForKey:@"info"] objectForKey:@"baojianlist1"];
        NSArray *array2 = [[data objectForKey:@"info"] objectForKey:@"hotList1"];
        NSArray *array3 = [[data objectForKey:@"info"] objectForKey:@"jianfeiList1"];
        NSArray *array4 = [[data objectForKey:@"info"] objectForKey:@"meirongList1"];
        NSArray *array5 = [[data objectForKey:@"info"] objectForKey:@"testList"];
        NSArray *array6 = [[data objectForKey:@"info"] objectForKey:@"zhenliaoList1"];
        NSMutableArray *banner = [NSMutableArray array];
        [banner addObjectsFromArray:array1];
        [banner addObjectsFromArray:array2];
        [banner addObjectsFromArray:array3];
        [banner addObjectsFromArray:array4];
        [banner addObjectsFromArray:array5];
        [banner addObjectsFromArray:array6];
        
        NSDictionary *firstDic = [banner firstObject];
        NSDictionary *lastDic = [banner lastObject];
        [_imageArray addObject:lastDic];
        [self.imageArray addObjectsFromArray:banner];
        [_imageArray addObject:firstDic];
        [self.tableView reloadData];
        
        
    } get:@"get"];
 
    //合作单位的数据解析
    [AsyncConnection asyncConnectionWithUrl:MB_DrugCompany name:@"company" parameters:nil block:^(id data) {
        
        NSArray *results = [data objectForKey:@"results"];
        
        for (NSDictionary *dic in results) {
            HomeModel *model = [[HomeModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.tableArray addObject:model];
        }
        [self.tableView reloadData];
    } get:@"get"];
    
    
    [AsyncConnection asyncConnectionWithUrl:@"http://mobi.111.com.cn/ApiControl?method=get.homepage.layer.model&encryptversion=2&sign=92BB794AB52566675158C0DE50F5A57E&timestamp=20150917091815&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854" name:@"ApiControl" parameters:nil block:^(id data) {
        
        NSDictionary *dic = [data objectForKey:@"data"];
        NSArray *array2 = [dic objectForKey:@"index_lb"];
        [self.thirdArray addObjectsFromArray:array2];
        [self.tableView reloadData];
        
    } get:@"get"];
    
    
    [AsyncConnection asyncConnectionWithUrl:@"http://59945590.146.shengyiquan.org/requestdata.aspx?action=GetCategory&PageIndex=1" name:@"zixunFile1" parameters:nil block:^(id data) {
        
        [self.ziXunArray addObjectsFromArray:data];
        
        NSMutableArray *titleArray = [NSMutableArray array];
        if (_ziXunArray.count != 0) {
            
            for (int i = 0; i < _ziXunArray.count; i++) {
                
            [titleArray addObject:[[_ziXunArray objectAtIndex:i] objectForKey:@"CategoryName"]];
                
            }
            
        }
        
        _scrollSC.buttons = (NSArray *)titleArray;
        
        [self webXinWenConnection:[[_ziXunArray objectAtIndex:0] objectForKey:@"CategoryID"]];
        
        [self.tableView reloadData];
        
    } get:@"get"];
    
    
}

- (void)webXinWenConnection:(NSString *)requestId
{

    
        NSString *site = [NSString stringWithFormat:@"http://59945590.146.shengyiquan.org/requestdata.aspx?action=GetNews&CategoryID=%@&PageIndex=1",requestId];
        [AsyncConnection asyncConnectionWithUrl:site name:@"zixunFile3" parameters:nil block:^(id data) {
            
            [self.secondZiXunArray removeAllObjects];
            [self.secondZiXunArray addObjectsFromArray:data];
            [self.tableView reloadData];
            
        } get:@"get"];
    
   
}

#pragma mark -
#pragma mark 创建TableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 20) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.nightBackgroundColor = UIColorFromRGB(0x343434);
    self.tableView.nightSeparatorColor = UIColorFromRGB(0x313131);
    [DKNightVersionManager addClassToSet:[UITableViewCell class]];
    [_tableView release];
    
    
   
}



#pragma mark - 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section == 0) {
        
        return 2;
    } else if (section == 1) {
    
        return 1;
    
    } else if (section == 2)
    {
    
        return _secondZiXunArray.count;
        
    }

    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 3;

}

#pragma mark - cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellin"];
            if (!cell) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellin"] autorelease];
            }
            
            cell.nightBackgroundColor = UIColorFromRGB(0x343434);
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = @"合作品牌";
            cell.textLabel.textColor = [UIColor orangeColor];
            cell.detailTextLabel.text = @"更多";
            return cell;
        } if (indexPath.row == 1) {
            
            static NSString *key = @"cell";
            CompanyCell *comCell = [tableView dequeueReusableCellWithIdentifier:key];
            if (!comCell) {
                comCell = [[[CompanyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:key] autorelease];
            }
//            comCell.userInteractionEnabled = NO;
            if (self.tableArray.count > 0) {
                for (int i = 0; i < 4; i++) {
                    HomeModel *model = [self.tableArray objectAtIndex:i];
                    
                    [comCell valueWithModel:model tag:i];
                }
            }
            comCell.target = self;
            comCell.action = @selector(tapAction:tag:);
            return comCell;
            
        }
        
    } else if (indexPath.section == 1) {
    
        static NSString *homeHouse = @"home";
        MoreProductCell *more = [tableView dequeueReusableCellWithIdentifier:homeHouse];
        if (more == nil) {
            
            
            more = [[MoreProductCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:homeHouse];
            
        }
        more.nightBackgroundColor = UIColorFromRGB(0x343434);
        if (_thirdArray.count != 0) {
            
            [more getArray:_thirdArray];
            
        }
        
        more.target = self;
        more.action = @selector(myTapAction:);
        return more;

    } else if (indexPath.section == 2) {
    
        static NSString *xinWen = @"xinwenId";
        UITableViewCell *xinWenCell = [tableView dequeueReusableCellWithIdentifier:xinWen];
        if (xinWenCell == nil) {
            
            
            xinWenCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:xinWen];
            
        }
        if (_secondZiXunArray.count != 0) {
            
            xinWenCell.textLabel.text = [[_secondZiXunArray objectAtIndex:indexPath.row] objectForKey:@"CategoryName"];
        
            
        }
        xinWenCell.textLabel.nightTextColor = [UIColor whiteColor];
        xinWenCell.nightBackgroundColor = UIColorFromRGB(0x343434);
        return xinWenCell;
    
    }
     return nil;
    
}

#pragma mark -
#pragma mark cell的选择事件

- (void)myTapAction:(NSDictionary *)dic
{


    WebViewController *web = [[WebViewController alloc] init];
    web.target = [dic objectForKey:@"content"];
    [web getSignal:[dic objectForKey:@"title"]];
    [self presentViewController:web animated:YES completion:nil];
    [web release];


}

- (void)tapAction:(HomeModel *)model tag:(NSString *)tag
{

    int i = [tag intValue];
    DrugListViewController *list = [[DrugListViewController alloc] init];
    list.word = [_drugIDArray objectAtIndex:i];
    [self presentViewController:list animated:YES completion:nil];
    [list release];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0 && indexPath.section == 0) {
        CompanyViewController *company = [[CompanyViewController alloc] init];
        company.companyArray = self.tableArray;
        [self presentViewController:company animated:YES completion:nil];
        [company release];
    } else if (indexPath.section == 2) {
    
        InformationController *infoC = [[InformationController alloc] init];
        [infoC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        [infoC getDic:[_secondZiXunArray objectAtIndex:indexPath.row] array:_secondZiXunArray];
        [self presentViewController:infoC animated:YES completion:^{
            
            
        }];
    
    }
    
}
#pragma mark -
#pragma mark 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            return 40;
            
        } else if (indexPath.row == 1) {
        
            if (self.view.frame.size.width > 375) {
                
                
                return 100;
                
            }
            return 80;
        
        }
        return 0;
    } else if (indexPath.section == 1) {
    
        if (_thirdArray.count > 4 ) {
            
            if ( _thirdArray.count % 4 == 0) {
                
                return (self.thirdArray.count / 4) * (self.view.frame.size.width - 40) / 6 + (self.thirdArray.count / 4) * 40;
                
            } else {
                
                return (self.thirdArray.count / 4 + 1) * (self.view.frame.size.width - 40) / 6 + (self.thirdArray.count / 4 + 1) * 40;
                
            }
            
            
        } else {
            
            return (self.view.frame.size.width - 40) / 6 + 40;
            
        }
        
 
    
    } else if (indexPath.section == 2) {
    
        return 47;
    
    }
    return 0;
}

#pragma mark -
#pragma mark  viewHeader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 460)];
        headView.backgroundColor = [UIColor whiteColor];
        headView.nightBackgroundColor = UIColorFromRGB(0x343434);
        
#pragma mark - 轮番图
        PicView *picView = [[PicView alloc] initWithFrame:CGRectMake(0, 0, headView.frame.size.width, 260)];
        [headView addSubview:picView];
        if (_imageArray.count != 0) {
            
            [picView valueWithArray:self.imageArray];
            
        }
        picView.delegate = self;
        [picView release];
#pragma mark - 分类
        NSArray *title = @[@"家庭药箱",@"感冒用药",@"维生素钙",@"慢性病药",@"女性专区",@"男性专区",@"儿童专区",@"对症下药"];
        NSArray *name = @[@"jia.jpg",@"ganmao.jpg",@"wsxg.jpg",@"disease.jpg",@"nv.jpg",@"nan.jpg",@"ertong.jpg",@"dzxy.jpg"];
        ColumnView *column = [[ColumnView alloc] initWithFrame:CGRectMake(0, picView.frame.size.height + picView.frame.origin.y + 10, headView.frame.size.width, 200) imageName:name text:title];
        column.delegate = self;
        [headView addSubview:column];
        [column release];
        
        return [headView autorelease];
        
    } else if (section == 1) {
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 200, 30)];
        label.text = @"贴心保健";
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithRed:0.6 green:0.5 blue:0.8 alpha:1];
        return [label autorelease];
        
    } else if (section == 2) {
        
        if (_backView == nil) {
            
            self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
            [_backView addSubview:_scrollSC];
            
        }
       
        
        return _backView;
        
    }
    
    else {
    
        return nil;
    
    }
    
}

- (void)didSelectItemAtIndex:(NSInteger)index
{
    
    [self webXinWenConnection:[[_ziXunArray objectAtIndex:index] objectForKey:@"CategoryID"]];

}

#pragma mark -
#pragma mark 点击分类 进入详情界面

- (void)valueWithTag:(NSInteger)tag
{
    NSString *file = [[NSBundle mainBundle] pathForResource:@"ColumnUrl" ofType:@"plist"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:file];
    switch (tag) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        {
            NSString *str = [NSString stringWithFormat:@"%ld",(long)tag];
            NSArray *arr = [dic objectForKey:str];
            ColumnDrugListViewController *columnDrug = [[ColumnDrugListViewController alloc] init];
#pragma mark - 传值
            columnDrug.cArray = arr;
            [self presentViewController:columnDrug animated:YES completion:nil];
            [columnDrug release];
        }
            break;
        case 8:
        {
            DiseaseListViewController *disease = [[DiseaseListViewController alloc] init];
            [self presentViewController:disease animated:YES completion:nil];
            [disease release];
        }
            
        default:
            break;
    }
}

#pragma mark -
#pragma mark 点击图片进入详情链接
- (void)valueWithUrl:(NSString *)url
{
    WebViewController *web = [[WebViewController alloc] init];
    web.target = url;
    [web getSignal:@"热门资讯"];
    [self presentViewController:web animated:YES completion:nil];
    [web release];
}

#pragma mark -
#pragma mark 头分区返回的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 460;
    }else
    {
        return 20;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}






@end
